package com.sophossystems.client.asmon.action;

import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.sophossystems.client.asmon.dto.UserDTO;
import com.sophossystems.client.asmon.model.User;
import com.sophossystems.client.asmon.service.LoginService;

public class LoginAction extends ActionSupport implements ModelDriven<User> {
	private static final long serialVersionUID = 1L;

	private static Logger log = Logger.getLogger(LoginAction.class);
	private User user = new User();
	@Override
	public String execute() throws Exception {
		
		log.debug("En la autentificacion User"+user.getUsername() +"  Password: "+ user.getPassword() );
		
		XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
		LoginService loginService = (LoginService)bf.getBean("loginService");
		UserDTO usuario = user.mapper();
		UserDTO autentificacion = null;
		String resultado = "";
		try{
			autentificacion = loginService.login(usuario);
		}catch (Exception e) {
			 log.debug("error al llamar loginService en login action, causa: " + e.getCause());
		}

//		System.out.println("En la autentificacion User"+usuario.getUsername() +"  Password: "+ usuario.getPassword());
		if (autentificacion != null) {
			Map session = ActionContext.getContext().getSession();
			session.put("logged-in", "true");
			log.debug("Autentificacion Correcta");
			resultado = SUCCESS;
		} else {
			log.debug("Mala autentificacion");
			resultado = ERROR;
		}
		
//		llena los posibles list a utilizar
		
		return resultado;
	}
	

	public String logout() throws Exception {

		Map session = ActionContext.getContext().getSession();
		session.remove("logged-in");
		return SUCCESS;
	}



	@Override
	public User getModel() {
		// TODO Auto-generated method stub
		return user;
	}

}
